import React from 'react'
import classNames from 'classnames'
import * as PropTypes from 'prop-types'
import {StoreManager} from '@/stores'
import {observer} from 'mobx-react'
import {Icon} from '@/components/Icon'
import {ButtonStore} from "@/components/Button";

@observer
export class Button extends React.Component {

    static propTypes = {
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]),
        modal: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol])
    }

    constructor(props) {
        super(props)
        this.store = StoreManager.create(new ButtonStore({
            ...props,
            name: props.name || Symbol('Button')
        }))
    }

    componentWillUnmount() {
        StoreManager.delete(this.store)
    }

    handleClick(event) {
        if (this.props.disabled || this.loading) {
            return
        }
        const {
            onClick,
            onLoaded,
            modal,
        } = this.props
        //记录事件元素,与动画效果关联
        window._eventSrcElement = event.currentTarget
        //如果指定modal属性,则尝试显示modal
        modal && this.showModal(event, modal)
        const result = onClick && onClick(event)
        if (result instanceof Promise) {
            this.store.changeLoading(true)
            result.then(() => {
                this.store.changeLoading(false)
                onLoaded && onLoaded(event)
            })
        }
    }

    showModal(event, storeKey) {
        const store = StoreManager.get(storeKey)
        store && store.toggle()
    }

    getClsssNames() {
        const {type, iconAlign} = this.props
        const classes = {}
        classes['btn'] = true
        if (!type) {
            classes['btn-default'] = true
        } else {
            classes[`btn-${type}`] = true
        }
        if (this.store.loading) {
            classes[`loading`] = true
        }
        if (iconAlign) {
            classes[`icon-${iconAlign}`] = true
        }
        return classNames(classes)
    }

    render() {
        const {
            children,
            icon,
            ...props
        } = this.props
        delete props.type
        delete props.className
        delete props.onClick
        delete props.onLoaded
        delete props.icon
        delete props.iconAlign
        delete props.children
        delete props.name
        delete props.modal
        return (
            <button type="button" className={this.getClsssNames()} onClick={this.handleClick.bind(this)} {...props}>
                <Icon type={this.store.loading ? 'loading' : icon}/><span>{children}</span>
            </button>
        )
    }
}